using System;
using System.Reflection;
using Masstransit.Courier.EventualConsistency.Proxy;
using MassTransit;
using MassTransitDemo.OrderService.Activities.CreateOrder;
using MassTransitDemo.OrderService.Command.CreateOrder;
using MassTransitDemo.Shared;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MassTransitDemo.OrderService
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddMassTransit(x =>
            {
                var currentAssembly = Assembly.GetExecutingAssembly();
                x.AddActivities(currentAssembly);
                x.AddConsumers(currentAssembly);
                x.AddRequestClient<CreateOrderCommand>();
                x.UsingRabbitMq((context, cfg) =>
                {
                    cfg.Host(Configuration["RabbitmqConfig:HostIP"], ushort.Parse(Configuration["RabbitmqConfig:HostPort"]), Configuration["RabbitmqConfig:VirtualHost"], h =>
                    {
                        h.Username(Configuration["RabbitmqConfig:Username"]);
                        h.Password(Configuration["RabbitmqConfig:Password"]);
                    });

                    cfg.ReceiveEndpoint("CreateOrderCommand", ep =>
                    {
                        ep.ConfigureConsumer<CreateOrderRequestProxy>(context);
                        ep.ConfigureConsumer<CreateOrderResponseProxy>(context);
                    });
                    cfg.ReceiveEndpoint("ReduceStock_execute", ep =>
                    {
                        ep.ExecuteActivityHost<ReduceStockActivity, ReduceStockModel>(new Uri(GetServiceAddress("ReduceStock_compensate")), context);
                    });
                    cfg.ReceiveEndpoint("ReduceStock_compensate", ep =>
                    {
                        ep.CompensateActivityHost<ReduceStockActivity, ReduceStockLog>(context, conf =>
                        {
                            conf.AddPipeSpecification(new RoutingSlipCompensateErrorSpecification<ReduceStockActivity, ReduceStockLog>());
                        });
                    });
                    cfg.ReceiveEndpoint("DeductBalance_execute", ep =>
                    {
                        ep.ExecuteActivityHost<DeductBalanceActivity, DeductBalanceModel>(new Uri(GetServiceAddress("DeductBalance_compensate")), context);
                    });
                    cfg.ReceiveEndpoint("DeductBalance_compensate", ep =>
                    {
                        ep.CompensateActivityHost<DeductBalanceActivity, DeductBalanceLog>(context, conf =>
                         {
                             conf.AddPipeSpecification(new RoutingSlipCompensateErrorSpecification<DeductBalanceActivity, DeductBalanceLog>());
                         });
                    });
                    cfg.ReceiveEndpoint("CreateOrder_execute", ep =>
                    {
                        ep.ExecuteActivityHost<CreateOrderActivity, CreateOrderModel>(context);
                    });
                });
            });
            services.AddMassTransitHostedService();
        }

        private string GetServiceAddress(string queueName)
        {
            return $"rabbitmq://{Configuration["RabbitmqConfig:HostIP"]}:{Configuration["RabbitmqConfig:HostPort"]}/{queueName}";
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
